/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: BearingClient.hpp,v 1.5 2009-11-14 14:29:17 ray Exp $
 *
 * \file
 * \brief MaCI - Bearing Interface Client header
 * \author Antti Maula <antti.maula@tkk.fi>
 */
#ifndef _MACI_INTERFACE_BEARINGCLIENT_HPP_
#define _MACI_INTERFACE_BEARINGCLIENT_HPP_

#include "MaCI.hpp"
#include "thread.hpp"
#include "sync.hpp"

// These are not necessarily required here, but defined to make the
// interface easier to include.
#include "BearingData.hpp"

#define PWR_LEVEL 0x12

// Forward declare gimi::GIMI
namespace gimi {
  class GIMI;
}

namespace MaCI {
  namespace Bearing {
    
    // Forward declaration.
    class CBearingData;
    class CBearingClient;

    
    /** Callback interface class for Bearing interface.
     *
     * This interface defines functions which can be used for
     * BearingClient callbacks. These functions are executed (more
     * detail per function basis) as new data arrives, and directly
     * from the context of the receiving thread. <b>Therefore, it is
     * important that the handling function is as simple and fast as
     * possible, as it will block the execution of the receiving
     * thread while executed.</b>
     */
    class CBearingClientCallback
    {
    public:

      CBearingClientCallback() {}
      virtual ~CBearingClientCallback() {}


      /** Handler function for BearingData event.
       *
       * This function is called when the BearingClient receives new
       * data from the server.
       *
       * \note <b>Keep this function simple & fast as it will block the 
       * data receiving thread while executing!</b>
       *
       * @param[in] aData       Constant reference to CBearingData element 
       *                        containing the received event.
       * @param[in] aDataSequence Sequence number of the received data. 
       *                        This should increment by one on each call.
       * @param[in] aBearingClient Reference to BearingClient 
       *                        instance which received this event.
       */
      virtual void OnBearingDataEvent(const CBearingData &aData, 
                                    const unsigned int aDataSequence,
                                    CBearingClient &aBearingClient) = 0;
    };

    /** Bearing event types.
     */
    enum EBearingEvent {
      KEventBearingData = 0 ///< BearingData element received and stored.
    };


    /** MaCI - Bearing Client interface.
     * 
     * This class contains the methods and types for using
     * a MaCI::Bearing service in the GIMnet.
     */
    class CBearingClient 
      : private gim::CSync,
        private gim::CThread,
        public MaCI::CMaCI
    {
    public:
      /** Constructor.
       * 
       * Constructor of the BearingClient. This requires;
       * a pointer to Initialized and connected GIMI, minor
       * number of this interface (Used as GIMI minor number)
       *
       * @param[in] aGIMIPtr Pointer to GIMI used for communication
       * @param[in] aInterfaceMinor Interface minor number. Usually
       *            used to indicate the instance of devices of same
       *            type. Can be left out if MaCISL is used.
       */     
      CBearingClient(gimi::GIMI *aGIMIPtr, const int aInterfaceMinor = -1);

      
      /** Destructor.
       */
      ~CBearingClient();

      /** Ask & receive syncronously
       * 
       * @param[out] aNumber    Reference to unsigned integer to contain the result.
       * @param[in] param      The parameter to be requested
       * @param[in] aTimeout_ms Timeout in milliseconds to wait for the synchronous
       *                        operation to complete.
       * @return                'true' on operation succesfully completed.
       */
      bool GetParamBySynchronousCall(unsigned int &aNumber, unsigned int parameter,
                                      unsigned int aTimeout_ms=1000);

     /** Ask & receive syncronously
       * 
       * @param[out] aNumber    Reference to unsigned integer to contain the result.
       * @param[in]             Maximum number of tags to be reported 
       * @param[in] aTimeout_ms Timeout in milliseconds to wait for the synchronous
       *                        operation to complete.
       * @return                'true' on operation succesfully completed.
       */
      bool GetTagsBySynchronousCall(unsigned int &aNumber,
                                    unsigned int numTags, 
                                    unsigned int aTimeout_ms);

     /** Ask & receive syncronously
       * 
       * @param[out] aEPC    Reference to char array to contain the EPC.
       * @param[in] aTimeout_ms Timeout in milliseconds to wait for the synchronous
       *                        operation to complete.
       * @return                'true' on operation succesfully completed.
       */
      bool GetEPCBySynchronousCall(unsigned char aEPC[12], 
                                   unsigned int aTimeout_ms);


      /** Receive BearingEvent.
       *
       * @param[out] aData     Reference to CBearingData to copy the data to.
       * @param aSequence      Pointer to sequence number. If this is NULL,
       *                       the most recent position is returned immediately.
       *                       If this is not NULL, the value pointed
       *                       should be set to 0 on the first call to this function.
       *                       After each call, the sequence number of the returned
       *                       data is stored here. If user wants to read all the
       *                       measures available, the value pointed should not be
       *                       modified after the first call.
       * @param[in] aTimeout_ms Timeout value. If the operation is not completed
       *                       before timeout is reached, the operation fails.
       * @return               true - Operation was succesfull, new data is copied
       *                       to provided location.
       *                       false - Operation failed; timeout or generic error
       *                       encountered.
       */
      bool GetBearingEvent(CBearingData &aData,
                         unsigned int *aSequence,
                         const unsigned int aTimeout_ms);
      
     /** Receive reply for a specific command.
       *
       * @param[out] aDummyData Reference to element to send.
       * @param[in] aMessageID  MessageID to set for sent command.
       * @param[in] aTimeout_ms Timeout in milliseconds to wait for message
       *                        to arrive.
       * @return                'true' if reply with given id was succesfully received.
       *                        'false' on any error (including Timeout)
       */
      bool GetCommandReply(CBearingData &aData, const int aMessageID, 
                                             const int aTimeout_ms);

      /** Send Bearing Command.
       *
       * Send the given BearingData element to server side of the Bearing interface.
       *
       * @param[in] aCmd        Reference to element to send.
       * @return                'true' if Message was succesfully sent to GIMnet. (No guarantee
       *                        of delivery is given though). 'false' on local connection
       *                        error or invalid datapacket (the container didn't contain
       *                        a TCommand element, which renders this command meaningless)
       */
      //      bool SendCommand(const CBearingData &aCmd);
      bool SendCommand(const CBearingData &aCmd, const int aMessageID = 0);    

      /** Assigns the Bearing client callback function. 
       *
       * This sets a function object for calling a position client
       * callback. If this is set, the interface calls the assigned
       * functions immediately when event is available.
       * 
       * \note As the function is run in the context of the receiving
       * thread, user must make sure that the callback function is
       * fast. As if the function executes too long, receiving events
       * is interrupted.
       *
       * @param[in] aBearingClientCallback Pointer to class implementing the interface
       *                                 CBearingClientCallback.
       */
      void SetBearingClientCallback(CBearingClientCallback *aBearingClientCallback) {
        iBearingClientCallback = aBearingClientCallback;
      }
      
    protected:
      /** Open client interface.
       *
       * Implementation of Open() for the class. This function is
       * called by the base class CMaCI::Open() function.
       */
      EMaCIError DoOpen(void);
      
      
      /** Close client interface.
       *
       * Implementation of Close() for the class. This function is
       * called by the base class CMaCI::Close() function.
       */
      EMaCIError DoClose(void);


    private:
      /// Thread runner function. Is in charge of receiving events.
      int ThreadFunction(const int aThreadNumber);
      int ProcessMessage(const gimi::GIMIMessage &msg);

      //data.
      unsigned int iBearingDataSequence; ///< Received data sequence
      unsigned int iBearingCommandSequence; ///< Last sent Command sequence.
      CBearingData iLastBearingData; ///< Last element available
      CBearingClientCallback *iBearingClientCallback; ///< Pointer to class instance containing callback functions.

      // Override copy & assignment operator privately to disable class copying.
      CBearingClient(const CBearingClient &)
        : CSync(1,1),
          CThread(1),
          CMaCI(NULL, 0, 0, ""),
          iBearingDataSequence(),
          iBearingCommandSequence(),
          iLastBearingData(),
          iBearingClientCallback() {}
      CBearingClient &operator=(const CBearingClient &) { return *this; }
    };


  }
}

#endif //_MACI_INTERFACE_BEARINGCLIENT_HPP_
